<template>
  <div class="ds">
    <a-button type="primary" class="add_ds" @click="onSetNewData" icon="plus">
      添加数据集
    </a-button>
    <a-button class="add_ds" @click="visible = true" icon="more" style="margin-right: 5px;">
      复制已有数据集
    </a-button>
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="DsList"
      :pagination="false"
      rowKey="id"
      :loading="table_loading"
      size="middle"
    >
      <span slot="action" slot-scope="row">
        <a @click="onUpdateDataset(row)">编辑</a>
        <a-divider type="vertical" />
        <a @click="onDeleteDataset(row)">删除</a>
      </span>
    </a-table>
    <a-modal width="800px" v-model="visible" title="复制数据集" @ok="handleOk" :confirmLoading="confirmLoading" okText="确定" cancelText="取消" :maskClosable="false">
      <a-transfer
        class="tree-transfer"
        :list-style="{
          width: '300px',
          height: '400px',
        }"
        :data-source="allDataset"
        :titles="['未选择', '已选择']"
        :target-keys="targetKeys"
        :render="item => item.title"
        :show-select-all="false"
        @change="handleChange"
      >
        <template
          slot="children"
          slot-scope="{ props: {direction, selectedKeys }, on: { itemSelect } }"
        >
          <a-tree
            v-if="direction === 'left'"
            blockNode
            checkable
            checkStrictly
            defaultExpandAll
            :checkedKeys="[...selectedKeys, ...targetKeys]"
            :treeData="treeData"
            @check="
            (_, props) => {
              onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
            }
          "
            @select="
            (_, props) => {
              onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
            }
          "
          />
        </template>
      </a-transfer>
    </a-modal>
    <!-- 抽屉 -->
    <a-drawer
      :title="form.title"
      placement="right"
      :maskClosable="false"
      :visible="drawer"
      width="75%"
      @close="onClose"
      :destroyOnClose="true"
    >
      <a-steps style="min-height:32px;" :current="current" size="small">
        <a-step v-for="item in steps" :key="item.title" :title="item.title" />
      </a-steps>
      <a-divider />
      <div class="steps-content" ref="steps-content">
        <addDs :current="current" :drawer="drawer" :form="form.data" />
      </div>
      <a-divider />
      <div class="steps-action">
        <a-button @click="onClose"  style="margin-right: 8px;">
          取消
        </a-button>
        <a-button v-if="current > 0" style="margin-right: 8px;" @click="prev">
          上一步
        </a-button>
        <a-button v-if="current < steps.length - 1" type="primary" @click.stop="next">
          下一步
        </a-button>
        <a-button
          v-if="current == steps.length - 1"
          type="primary"
          @click="onSaveDs"
          :loading="loadBtn"
        >
          保存
        </a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script>
const columns = [
        {
          title: '数据集名称',
          dataIndex: 'name',
          sorter: true
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          sorter: true
        },
        {
          title: '更新时间',
          dataIndex: 'updatedAt',
          sorter: true
        },
        { title: '说明', dataIndex: 'remark' },
        {
          title: '操作',
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
        }
      ]
import { mapActions, mapMutations, mapState } from 'vuex'
import addDs from './selectDs/addDs'
import bus from "@/views/components/bus"
import store from "@/store"

  export default {
    components: {
      addDs
    },
    data() {
      return {
        drawer: false,
        columns,
        current: 0,
        table_loading: false,
        confirmLoading: false,
        steps: [
          {
            title: '基本信息',
            list: '基本信息',
          },
          {
            list: '查询配置',
            title: '查询配置',
          },
          {
            title: '筛选字段',
            list: '筛选字段列表',
          },
          {
            list: '输出字段列表',
            title: '输出字段',
          }
        ],
        form: {
          title: '添加数据集',
          statusBtn: false,
          loadingBtn: false,
          data: {
            name: '',
            type: null,
            remark: null,
            datasourceId: null,
            config: {
              config: {
                indicators: [{
                  id: Math.random().toString(36).substr(2),
                  event: "",
                  measure: [],
                  filter: {
                    condition: 'AND',
                    rules: []
                  }
                }],
                dimensions: [],
                filter: {
                  condition: 'AND',
                  rules: []
                },
                display: {
                  orderby: '',
                  order: 'DESC',
                  limit: 100
                },
              },
              time: {
                start: null,
                end: null,
                unit: "day"
              }
            },
            filter: [],
            output: [],
          }
        },
        rules: {
          name: []
        },
        allDataset: [],
        treeData: [],
        targetKeys: [],
        selectedKeys: [],
        visible: false,
        loadBtn: false,
        rowSelection: {}
      }
    },
    watch: {
      // 关闭抽屉清空表单
      drawer (val) {
        if (!val) {
          localStorage.setItem('sql_query', '')
          this.UPDATE_REPORTFORM({})
          this.SET_FILTER_COLUMNS([])
          this.SET_TABLE_LIST([])
          this.SET_TABLE_COLUMNS([])
          this.$refs.ruleForm && this.$refs.ruleForm.clearValidate()
          this.current = 0
          this.loadBtn = false
        }
      },
      'form.data.datasourceId'(val,old){
        if (old != undefined) {
          if (old != val) {
            this.form.data.type = ''
          }
        }
      },
      'form.data': {
        handler (value) {
          this.SET_REPORTFORM(value)
        },
        deep: true
      },
      current (value) {
        this.$nextTick(() => {
          if (this.$refs['steps-content']) {
            if (value==1 && this.form.data.type === 0) {
              this.$refs['steps-content'].style.overflow = 'hidden';
            } else {
              this.$refs['steps-content'].style.overflow = 'auto';
            }
          }
        })
      },
      visible (value) {
        if (value) {
          this.targetKeys = []
          this.getAllDataset().then(res => {
            const data = res.data
            const result = []
            for (let i in data){
              result[i] = {
                title: data[i].reportName,
                key: (data[i].id).toString(),
                children:[],
                checkable:false,
                disableCheckbox:true,
                disabled:true

              }
              let datasets = data[i].datasets
              for (let j in datasets){
                const child = {
                  title: datasets[j].name,
                  key: (datasets[j].id).toString(),
                }
                result[i].children.push(child)
              }
            }
            this.flatten(JSON.parse(JSON.stringify(result)));
            this.treeData = result;
            })
            .catch(err => {
              console.log(err)
              this.$message.error('获取源数据集列表失败，原因：' + err.msg + '！')
            })
        }
      }
    },
    computed: {
      ...mapState('custom', ['haveDs', 'DsList', 'rulesBoolean', 'reportForm']),
    },
    mounted () {
      this.getDsList({id: this.$route.query.id})
      bus.$on('onChangeDatasetType',(value)=>{
        if (value == 0) {
          this.form.data.config = {
            sql: null,
            version: 1
          };
        } else if (value == 1) {
          this.form.data.config = {
            config: {
              indicators: [{
                id: Math.random().toString(36).substr(2),
                event: "",
                measure: [],
                filter: {
                  condition: 'AND',
                  rules: []
                }
              }],
              dimensions: [],
              filter: {
                condition: 'AND',
                rules: []
              },
              display: {
                orderby: '',
                order: 'DESC',
                limit: 100
              }
            },
            time: {
              start: null,
              end: null,
              unit: 'day'
            }
          };
        } else if (value == 2) {
          this.form.data.config = {
            config: {
              dimension: '',
              filter: {
                condition: "AND",
                rules: []
              },
              funnel: {}
            },
            time: {
              start: null,
              end: null,
              unit: "none"
            }
          };
        } else if (value == 3) {
          this.form.data.config = {
            config: {
              events: [],
              endpoint: {
                type: 0,
                event: "",
                filter: {
                  condition: "AND",
                  rules: []
                }
              },
              dimension: [],
              filter: {
                condition: "AND",
                rules: []
              }
            },
            time: {
              start: null,
              end: null
            },
            limit: {
              node: 3,
              level: 10
            }
          };
        } else if (value == 4) {
          this.form.data.config = {
            config: {
              first_event: {
                indicators: [
                  {
                    id: Math.random()
                      .toString(36)
                      .substr(2),
                    event: "",
                    measure: [],
                    filter: {
                      condition: "AND",
                      rules: []
                    }
                  }
                ]
              },
              second_event: {
                indicators: [
                  {
                    id: Math.random()
                      .toString(36)
                      .substr(2),
                    event: "",
                    measure: [],
                    filter: {
                      condition: "AND",
                      rules: []
                    }
                  }
                ]
              },
              by_field: ["总体"],
              dimensions: [],
              user_filter: {
                condition: "AND",
                rules: []
              },
              is_wastage: 0
            },
            time: {
              start: null,
              end: null,
              unit: 'day',
              duration: 1,
              customDuration: 1
            }
          };
        }
        this.form.data.filter = [];
        this.form.data.output = [];
      });
    },
    methods: {
      ...mapMutations('sql_query', ['SET_FILTER_COLUMNS', 'SET_TABLE_LIST', 'SET_TABLE_COLUMNS']),
      ...mapActions('custom', ['getDsList', 'setReportDs', 'deleteReportDs', 'getUpdateReportDs', 'saveData', 'updateData', 'deleteData', 'get_be_using_report', 'getAllDataset', 'deleteDataSet']),
      ...mapMutations('custom', ['SET_DS_LIST', 'ADD_SET_LIST', 'SET_REPORT', 'SET_REPORTFORM', 'UPDATE_REPORTFORM']),
      flatten(list = []) {
        list.forEach(item => {
          this.allDataset.push(item);
          this.flatten(item.children);
        });
      },
      isChecked(selectedKeys, eventKey) {
        return selectedKeys.indexOf(eventKey) !== -1;
      },
      onChecked(_, e, checkedKeys, itemSelect) {
        const { eventKey } = e.node;
        itemSelect(eventKey, !this.isChecked(checkedKeys, eventKey));
      },
      handleOk () {
        this.confirmLoading = true;
        let arr = []
        this.targetKeys.forEach(v => {
          arr.push({id: v})
        })
        this.SET_DS_LIST(arr)
        this.setReportDs(this.$route.query.id)
          .then(res => {
            this.getDsList({id: this.$route.query.id})
              .then(() =>{
                this.confirmLoading = false;
                this.visible = false;
              })
          })
      },
      onSetNewData () {
        this.form = {
          title: '添加数据集',
          statusBtn: false,
          loadingBtn: false,
          data: {
            name: '',
            type: null,
            remark: null,
            datasourceId: null,
            config: {
              config: {
                indicators: [{
                  id: Math.random().toString(36).substr(2),
                  event: "",
                  measure: [],
                  filter: {
                    condition: 'AND',
                    rules: []
                  }
                }],
                dimensions: [],
                filter: {
                  condition: 'AND',
                  rules: []
                },
                display: {
                  orderby: '',
                  order: 'DESC',
                  limit: 100
                },
              },
              time: {
                start: null,
                end: null,
                unit: "day"
              }
            },
            filter: [],
            output: [],
          }
        };
        this.drawer = true;
        this.UPDATE_REPORTFORM(this.form.data)
      },
      onClose () {
        this.$confirm({
          title: '提示',
          content: '关闭后数据会丢失，确定关闭吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            this.drawer = false
          },
          onCancel: () => {},
        })
      },
      onTableHandle () {},
      next (e) {
        if (this.current == 0) {
          bus.$emit('rulesForm', true)
          if (this.rulesBoolean) {
            this.current++;
          }
        } else if (this.current == 1 && this.reportForm.type == 1) {
          if(this.checkQueryConfig()) {
            this.current++;
          } else {
            this.$message.error("参数配置不正确，请验证后重试！");
            return;
          }
        } else if (this.current === 1 && this.reportForm.type === 0){
          bus.$emit('filterCheck',  res => {
            if (res){
              this.current++
            }else {
              this.$message.error("请校验SQL后再进行下一步操作");
            }
          })
        }else {
          this.current++;
        }
      },
      prev () {
        this.current--;
      },
      onSaveDs () {
        this.loadBtn = true
        if (this.form.title == '编辑数据集') {
          this.get_be_using_report({id: this.reportForm.id})
            .then(res=> {
              let useReport = res.data
              let filterCurrentReport = useReport.filter(report => {
                if (report.id != this.$route.query.id) {
                  return report
                }
              })
              if (filterCurrentReport.length) {
                let reportName = filterCurrentReport.map(item => {
                  return item.name
                })
                this.$confirm({
                  title: '提示',
                  content: `修改数据集可能导致图表不可用，确定要修改吗？`,
                  okText: '确定',
                  cancelText: '取消',
                  onOk: () => {
                    this.updateData({reportId: this.$route.query.id})
                      .then(res => {
                        this.drawer = false
                        this.getDsList({id: this.$route.query.id})
                      })
                      .catch(err => this.$message.error('数据集修改失败，原因：' + err.msg + '！'))
                      .finally(res =>{
                        this.loadBtn = false
                      })
                  },
                  onCancel: () => {
                    this.loadBtn = false
                  },
                })
              } else {
                this.updateData({reportId: this.$route.query.id})
                  .then(res => {
                    this.drawer = false
                    this.getDsList({id: this.$route.query.id})
                  })
                  .catch(err => this.$message.error('数据集修改失败，原因：' + err.msg + '！'))
                  .finally(res =>{
                    this.loadBtn = false
                  })
              }
            })
            .catch(err => {
              console.error(err)
            })
          return

        } else {
          this.saveData({reportId: this.$route.query.id})
            .then(res => {
              this.drawer = false
              this.getDsList({id: this.$route.query.id})
            })
            .catch(err => this.$message.error('数据集保存失败，原因：' + err.msg + '！'))
            .finally(res => {
              this.loadBtn = false
            })
        }

      },
      onUpdateDataset ( row ) {
        this.form.title = '编辑数据集';
          this.getUpdateReportDs({ id: row.id })
          .then(res => {
            const {data} = res
            if (data.type == 0) {
              let config = {
                version: 1
              }
              try {
                config = JSON.parse(data.config)
              }catch (e){
                config.sql = data.config
              }
              this.form.data = {...data, config:config, filter: JSON.parse(data.filter), output: JSON.parse(data.output)};
            } else {
              if (data.type == 4) {
                let config = JSON.parse(data.config);
                let isWsatage = config.config.is_wastage == true ? 1 : 0;
                config.config.is_wastage = isWsatage;
                this.form.data = {...data, config, filter: JSON.parse(data.filter), output: JSON.parse(data.output)};
              } else {
                this.form.data = {...data, config: JSON.parse(data.config), filter: JSON.parse(data.filter), output: JSON.parse(data.output)};
              }
            }
            // this.UPDATE_REPORTFORM(JSON.parse(JSON.stringify(this.form.data)))
            this.drawer = true
          })
          .catch(err => {
            console.error(err)
            this.$message.error('报表获取失败，原因：' + err.msg + '！')})
      },
      onDeleteDataset ( row ) {
        this.$confirm({
          title: '删除提示',
          content: '删除数据后无法恢复，您确定要继续吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            let datasetArr = this.DsList.filter(item=>{
              if(item.id != row.id){
                return item
              }
            })
            this.deleteDataSet({datasetId:row.id})
              .then(res => {
                this.$message.success('数据集删除成功')
                this.getDsList({id: this.$route.query.id})
              })
              .catch(err => this.$message.error('数据集删除失败，原因：' + err.msg + '！'))
          },
          onCancel: () => {},
        })
      },
      handleChange(nextTargetKeys, direction, moveKeys) {
        this.targetKeys = nextTargetKeys;
      },
      handleSelectChange(sourceSelectedKeys, targetSelectedKeys) {
        this.selectedKeys = [...sourceSelectedKeys, ...targetSelectedKeys];
      },
      handleScroll(direction, e) {},
      checkQueryConfig_deep(obj){
        if(!obj){
          return true;
        }
        if(obj.condition&&obj.rules&&obj.rules.length==0){
          return true
        }
        let deep_bool = true;

        if(obj.rules&&obj.rules.length>0){
          obj.rules.map((_i,_in)=>{
              deep_bool = this.checkQueryConfig_deep(_i);
          })
        }
        if(obj.property === ''  || obj.operator === '') {
          deep_bool = false;
        } else if(obj.operator&&obj.operator.indexOf("is") !== 0 &&
          ((obj.value === '' || obj.value === null)
            && obj.values.length === 0)) {
          deep_bool = false;
        }
        return deep_bool;
      },
      // TODO
      checkQueryConfig: function() {
        let config = this.form.data.config.config
        //验证indicators
        for(let i = 0; i < config.indicators.length; i++) {
          if(config.indicators[i].event === '' || config.indicators[i].measure.length === 0) {
            return false;
          }
          //验证indicator中的filter
          let indicators_bool = this.checkQueryConfig_deep(config.indicators[i].filter);
          if(!indicators_bool){
            return false;
          }
        }
        //验证filter
        let filter_bool = this.checkQueryConfig_deep(config.filter);
        if(!filter_bool){
          return false
        }
        if(config.display.order === undefined || config.display.order === '') {
          return false;
        }
        if(config.display.limit === undefined || config.display.limit <= 0) {
          return false;
        }
        return true;
      },
    },
  }
</script>

<style scoped>
  .ds {
    width: 100%;
  }

  .add_ds {
    float: right;
    margin-bottom: 24px;
  }

  .ant-drawer>>>.ant-drawer-body{
  height: calc(100% - 55px);
  display: flex;
  flex-direction: column;
  padding: 24px 24px 12px 24px;
}

.ant-form{
  height: 100%;
  display: flex;
  flex-direction: column;
}

.submit_style{
  margin-bottom: 0;
  flex: 1;
}

.submit_style>>>.ant-col.ant-col-18.ant-form-item-control-wrapper{
  width: 100%;
  height: 100%;
}

.submit_style>>>.ant-form-item-control{
  display: flex;
  height: 100%;
  align-items: flex-end;
}

.submit_style>>>span.ant-form-item-children{
  width: 100%;
}

.save_button,
.cancal_button {
  float: right;
}

.cancal_button {
  margin-right: 15px;
}

.steps-content{
  /* flex-grow: 1; */
  overflow: auto;
  height: calc(100% - 138px);
}

.steps-action{
  align-self: flex-end;
}

.ant-steps-item.ant-steps-item-wait>>>.ant-steps-item-title {
  font-size: 14px;
}

.ant-steps-item.ant-steps-item-process.ant-steps-item-active>>>.ant-steps-item-title{
  font-size: 14px;
}

.ant-divider-horizontal{
  margin: 24px 0px 12px 0px;
}

.ds>.ant-table-wrapper>>>.ant-spin-nested-loading {
  margin-top: 30px;
}

.ds>>>.steps-content>span {
  font-size: 20px !important;
}

  /*.tree-transfer .ant-transfer-list:first-child {*/
  /*  width: 50%;*/
  /*  flex: none;*/
  /*}*/

</style>

<style>
.ant-transfer {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
</style>
